package com.cheyun.netsalev3.view

import android.content.Intent
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.FragmentLazyStatePageAdapter
import com.cheyun.netsalev3.bean.CustomListParam
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.databinding.CustomerPopItemBinding
import com.cheyun.netsalev3.databinding.FragmentHomeCustomerBinding
import com.cheyun.netsalev3.utils.BaseFragment
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.home.CustomerItemFragment
import com.cheyun.netsalev3.view.search.FilterActivity
import com.cheyun.netsalev3.viewmodel.CustomerItemFragmentViewModel
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import java.io.Serializable


/**
 * 线索
 *
 */
class HomeCustomerFragment : BaseFragment<FragmentHomeCustomerBinding>() {
    override fun initContentView(): Int {
        return R.layout.fragment_home_customer
    }

    var popupWindow: PopupWindow? = null
    //跟进：archive.purge
    //订车：archive.order
    //提车：archive.thenend
    //战败：archivecheck.fail
//    var titles = arrayOf("跟进", "订车", "提车")
//    var nkeys = arrayOf("archive.purge", "archive.order", "archive.thenend")
    private var listFragmet = ArrayList<Fragment>()

    var titles = ArrayList<String>()
    var nkeys = ArrayList<String>()

    //分类选中的值
    var type1HashMap = HashMap<String, String>()
    var type1HashMapDesc = ArrayList<DialogParam>()
    //时间选中的值
    var type2HashMap = HashMap<String, String>()
    //用户选中的值
    var type3HashMap = HashMap<String, String>()
    //排序选中的值
    var type4HashMap = HashMap<String, String>()

    var sort = ""
    var order = ""

    init {
        titles.add("全部")
        nkeys.add("archive.index")
    }

    override fun initViewModel(): ViewModel? {
        activity?.apply {
            val factory = InjectorUtils.getCustomerItemFragmentViewModelFactory(nkeys)
            return ViewModelProviders.of(this, factory).get(CustomerItemFragmentViewModel::class.java)
        }
        return null
    }

    override fun initData() {
        binding.viewModel?.sort?.observe(this, Observer { it ->
            if(it.equals("followtime")) binding.txtSort.text = "最后跟进时间"
            if(it.equals("remindetime")) binding.txtSort.text = "下次沟通时间"
            if(it.equals("dateline")) binding.txtSort.text = "建档时间"
        })
        binding.viewModel?.order?.observe(this, Observer { it ->
            if(it.equals("desc")) binding.ivOrder.setImageDrawable(resources.getDrawable(R.drawable.paixu_daoxu))
            if(it.equals("asc")) binding.ivOrder.setImageDrawable(resources.getDrawable(R.drawable.paixu_zhengxu))
        })
    }

    override fun lazyInit() {
        Log.i("HomeCustomerFragment","override lazyinit")
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this).statusBarColor(R.color.colorbg_blue)
                .fitsSystemWindows(true)
                .init()

    }

    override fun initView() {
        for (i in titles.indices) {
            listFragmet.add(CustomerItemFragment.newInstance(nkeys[i]))
        }

        val pagerAdapter = FragmentLazyStatePageAdapter(childFragmentManager, listFragmet,titles)
        binding.viewPager.offscreenPageLimit = 1
        binding.viewPager.adapter = pagerAdapter


        binding.tabLayout.setupWithViewPager(binding.viewPager)
        //选中的位置
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                var pos = binding.tabLayout.selectedTabPosition
                Log.i("current pos =>",pos.toString())
                var nke = nkeys[pos]
                if(binding.viewModel?.totlelist!![nke] ==null){
                    binding.totleText.text = ""
                }else{
                    binding.totleText.text = titles[pos] + binding.viewModel?.totlelist!![nke]?.value + "人"
                }
                showTips()
            }
        })

        if(nkeys.size>0){
            for (index in 0 until nkeys.size){
                var nke = nkeys[index]
                binding.viewModel?.totlelist!![nke]?.observe(this@HomeCustomerFragment, Observer {
                    if(index == binding.tabLayout.selectedTabPosition){
                        Log.i("current pos2 =>",index.toString());
                        binding.totleText.text = titles[index] + it.toString() + "人"
//                        if(it!=null) {
//                            showTips()
//                        }
                        binding.txtTotal.text = it.toString()
                        binding.txtTotal1.text = it.toString()
                    }
                })

                binding.viewModel?.toplist!![nke]?.observe(this@HomeCustomerFragment, Observer {
                    for (normal in it){
                        if(normal.ikey.equals("FS1"))
                            binding.txtFS1.text = normal.tc.toString()
                        if(normal.ikey.equals("FS2"))
                            binding.txtFS2.text = normal.tc.toString()
                        if(normal.ikey.equals("FS3"))
                            binding.txtFS3.text = normal.tc.toString()
                        if(normal.ikey.equals("FS7"))
                            binding.txtFS7.text = normal.tc.toString()
                    }

                })
                binding.viewModel?.focus_total!![nke]?.observe(this@HomeCustomerFragment, Observer {
                    if(index == binding.tabLayout.selectedTabPosition){
                        binding.txtImportment.text = "重点客户 " + it.toString()
                    }
                })
            }
        }

        binding.searchBut.setOnClickListener {
//            showPop(it)
            var intent = Intent(context, CustomListActivity::class.java)
            intent.putExtra("list", binding.viewModel?.poplists as Serializable)
            startActivityForResult(intent, 101)
        }
        binding.searchText.setOnClickListener {
            var intent = Intent(context, SearchActivity::class.java)
            intent.putExtra("nkey", "archive.index")
            startActivity(intent)
        }

        binding.filterType1.setOnClickListener {
            var y = getPos(it)
            onFilter(1,y)
        }
        binding.filterType2.setOnClickListener {
            var y = getPos(it)
            onFilter(2,y)
        }
        binding.filterType3.setOnClickListener {
            var y = getPos(it)
            onFilter(3,y)
        }
    }
    fun getPos(it:View):Int{
        val location = IntArray(2)
        it.getLocationOnScreen(location)
        var x = location[0]
        var y = location[1]
        Log.d("123", "getLocationOnScreen  x = " + x.toString() + " ; " + " y = " + y)
        it.getLocationInWindow(location)
        x = location[0]
        y = location[1]
        Log.d("123", "getLocationInWindow  x = " + x.toString() + " ; " + " y = " + y)

        Log.d("123", "left:" + it.getLeft())
        Log.d("123", "right:" + it.getRight())
        Log.d("123", "Top:" + it.getTop())
        Log.d("123", "Bottom:" + it.getBottom())
        Log.d("123", "Width:" + it.getWidth())
        Log.d("123", "Height:" + it.getHeight())
        return y;
    }

    fun onFilter(filterType: Int,top:Int) {
        var intent = Intent(context, FilterActivity::class.java)
        intent.putExtra("type", filterType)
        intent.putExtra("type1Data", type1HashMap as Serializable)
        intent.putExtra("type1DataDesc", type1HashMapDesc as Serializable)
        intent.putExtra("type2Data", type2HashMap as Serializable)
        intent.putExtra("type3Data", type3HashMap as Serializable)
        intent.putExtra("type4Data", type4HashMap as Serializable)
        intent.putExtra("top",top);
        //当前已选中的项
        startActivityForResult(intent, 102)
    }

    /**
     * 显示弹窗
     */
    private fun showPop(view: View) {
        if (popupWindow == null) {
            var popbingding =
                    DataBindingUtil.inflate<CustomerPopItemBinding>(LayoutInflater.from(context),
                            R.layout.customer_pop_item, null, false)
            popupWindow = PopupWindow(popbingding.root,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT)
            popbingding.customText.setOnClickListener {
                //自定义选项
                var intent = Intent(context, CustomListActivity::class.java)
                intent.putExtra("list", binding.viewModel?.poplists as Serializable)
                startActivityForResult(intent, 101)
                popupWindow!!.dismiss()
            }
            popbingding.searchText.setOnClickListener {
                //高级搜索
                var intent = Intent(context, AdvancedSearchActivity::class.java)
                intent.putExtra("nkey", "archive.index")
                startActivity(intent)
                popupWindow!!.dismiss()
            }
        }
        popupWindow?.isOutsideTouchable = true
        context?.apply {
            popupWindow?.showAsDropDown(view, FunctionUtils.dip2px(this, -80f), -10, Gravity.BOTTOM)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == 101) {
            var list = data?.getSerializableExtra("poplist") as List<CustomListParam>
            MySharedPreferences.setListItem(list)
            binding.viewModel?.onResult(list)
            for (fragment in listFragmet) {
                fragment?.onActivityResult(requestCode, resultCode, data)
            }
        }else if (resultCode == 102) {
            type1HashMap = data?.getSerializableExtra("type1Data") as HashMap<String, String>
            type1HashMapDesc = data?.getSerializableExtra("type1DataDesc") as ArrayList<DialogParam>
            type2HashMap = data?.getSerializableExtra("type2Data") as HashMap<String, String>
            type3HashMap = data?.getSerializableExtra("type3Data") as HashMap<String, String>
            type4HashMap = data?.getSerializableExtra("type4Data") as HashMap<String, String>
            if(type2HashMap.containsKey("datetype")){
                binding.viewModel?.onChangeSort(type2HashMap.get("datetype")!!)
            }
            for (fragment in listFragmet) {
                fragment?.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

    private fun showTips(){
        binding.totleText.setVisibility(View.VISIBLE)
        binding.totleText.clearAnimation()
        val animation = AlphaAnimation(1f, 0f)
        animation.duration = 3000
        binding.totleText.startAnimation(animation)
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {

            }

            override fun onAnimationEnd(animation: Animation) {
                binding.totleText.setVisibility(View.GONE)
            }

            override fun onAnimationRepeat(animation: Animation) {

            }
        })
    }
}
